package org.hawk.gwt.ppc.mojo;

import org.apache.maven.plugin.logging.Log;

/**
 * Logger bridge to the maven logger. Instantiated through reflection.
 * Used by preprocessor's logging subsystem to log messages to maven console.
 * 
 * @author alex.bereznevatiy@gmail.com
 */
public class Logger {
	
	/**
    * Logs an error.
    */
	private static final int LOG_ERROR = 0x0F;

   /**
    * Logs a warning.
    */
	private static final int LOG_WARN = 0x01F;

   /**
    * Logs information.
    */
	private static final int LOG_INFO = 0x03F;

   /**
    * Logs information related to lower-level operation.
    */
	private static final int LOG_TRACE = 0x07F;

   /**
    * Logs detailed information that could be useful during debugging.
    */
	private static final int LOG_DEBUG = 0x0FF;
	
	private static Logger instance;
	
	private Log log;
	
	private Logger() {}
	
	/**
	 * @return <i>singleton</i> instance of logger.
	 */
	public static Logger get() {
		if (instance == null) {
			instance = new Logger();
		}
		return instance;
	}
	
	void configure(Log log) {
		this.log = log;
	}
	
	
	/**
	 * Logs message with level specified if level is allowed.
	 */
	public void log(int level, String message, Throwable th) {
		switch(level) {
		case LOG_ERROR:
			if (th == null) log.error(message); 
			else log.error(message, th);
			return;
		case LOG_WARN:
			if (th == null) log.warn(message); 
			else log.warn(message, th);
			return;
		case LOG_INFO:
			if (th == null) log.info(message); 
			else log.info(message, th);
			return;
		case LOG_TRACE:
		case LOG_DEBUG:
			if (th == null) log.debug(message); 
			else log.debug(message, th);
			return;
		default:
			throw new IllegalArgumentException("Unknown level: " + level);
		}
	}
	
	/**
	 * @return <code>true</code> if passed level is valid and allowed.
	 * Otherwise returns <code>false</code>.
	 */
	public boolean isEnabled(int level) {
		switch(level) {
		case LOG_ERROR:
			return log.isErrorEnabled();
		case LOG_WARN:
			return log.isWarnEnabled();
		case LOG_INFO:
			return log.isInfoEnabled();
		case LOG_TRACE:
		case LOG_DEBUG:
			return log.isDebugEnabled();
		default:
			return false;
		}
	}
}